import asyncio, pyautogui, random, os, time, json, time
from datetime import datetime

from core.base_controller import BaseController
from core.utils import focus_wow, get_image_pos
from db import SchedulesDB
from controllers.reset_wow_exe.reset_wow_exe_controller import ResetWowExeController
from controllers.craft_group.craft_group_controller import CraftGroupController
from controllers.login_role_controller import LoginRoleController
from controllers.key_press_list.key_press_list_controller import KeyPressListController
from core.wow_helper import WowHelper

class ScheduleController(BaseController):
  def __init__(self, task_list, ws_client):
    super().__init__(task_list, ws_client)
    self.check_state = {"ddd": 23}
    self.locked = False
    self.last_send_client_lose_time = 0

  async def toggle_schedule_locked(self, extra_data={}):
    locked = extra_data.get("locked", "0") == "1"
    self.locked = locked

  async def hot_refresh_schedule(self, extra_data={}):
    refresh_ids = extra_data.get("ids", [])
    cur_date = datetime.now().strftime("%Y-%m-%d")
    for id in refresh_ids:
      state_key = f"{cur_date}_{id}"
      if state_key in self.check_state:
        del self.check_state[state_key]
        
  def clear_date_history_from_state(self):
    cur_date = datetime.now().strftime("%Y-%m-%d")
    keys_to_delete = [k for k in self.check_state if not k.startswith(f"{cur_date}_")]
    for k in keys_to_delete:
        del self.check_state[k]
        
  def check_wow_client_lose(self):
    lose_pos = get_image_pos("images_2/client_lose.png", confidence=0.6)
    if lose_pos is None:
      self.last_send_client_lose_time = 0
    if (lose_pos is not None) and (int(time.time()) - self.last_send_client_lose_time > 60 * 60 * 2):
      send_status = WowHelper.send_email("wow client lose")
      if send_status:
        self.last_send_client_lose_time = int(time.time())
    
  async def trigger(self):
    self.check_wow_client_lose()
    if self.locked:
      return
    self.clear_date_history_from_state()
    db_schedule_list = await SchedulesDB.filter(status=1)
    cur_date = datetime.now().strftime("%Y-%m-%d")
    # print(self.check_state)
    next_schedule_list = []
    for schedule in db_schedule_list:
      schedule_start_time = datetime.strptime(schedule.start_time, "%Y-%m-%d %H:%M:%S")
      # 每日任务
      if schedule.schedule_type == 2:
        time_str = schedule_start_time.time().strftime("%H:%M:%S")
        schedule_start_time = datetime.strptime(cur_date + " " + time_str, "%Y-%m-%d %H:%M:%S")
      state_key = f"{cur_date}_{schedule.id}"
      if state_key not in self.check_state:
        if datetime.now() > schedule_start_time:
          self.check_state[state_key] = 1
        else:
          self.check_state[state_key] = 0
      else:
        if datetime.now() > schedule_start_time and self.check_state[state_key] == 0:
          self.check_state[state_key] = 1
          next_schedule_list.append(schedule)
    await self.run_schedule(next_schedule_list)
    # print("next_schedule_list", [x.schedule_name for x in next_schedule_list])
    # print("db_schedule_list", len(db_schedule_list))
    # await self.stop_all_task()  # 停止之前所有任务
    # await self.log("ScheduleController Start")
    # task = asyncio.create_task(self.loop_cmds())  # 创建任务
    # self.add_task(task)  # 添加任务到列表

  async def run_schedule(self, schedules):
    if len(schedules) == 0:
      return
    schedule = schedules[0]
    async def run_schedule_task(schedule):
      await self.log(f"Running schedule: {schedule.schedule_name}")
      extra_data = self.parse_schedule_extra_data(schedule)
      await ResetWowExeController(task_list=self.task_list, ws_client=self.ws_client).loop_cmds("wow1")
      print("extra_data", extra_data)
      login_role_name = extra_data.get('extra_data', {}).get("login_role_name", "")
      if login_role_name:
        await LoginRoleController(
          role_name=login_role_name, 
          extra_actions=lambda: None,
          ws_client=self.ws_client,
          log_prefix="{} schedule start_role_pet_battle Log:".format(login_role_name),
        ).start(only_login=True)
        
      if extra_data.get("type", "") == "start_craft_group":
        await self.log(f"Running craft group")
        craft_group_controller = CraftGroupController(task_list=self.task_list, ws_client=self.ws_client)
        craft_group_controller.set_extra_data(extra_data=extra_data.get("extra_data", {}))
        await craft_group_controller.auto_craft(extra_data=extra_data.get("extra_data", {}))
      if extra_data.get("type", "") == "start_key_press_list":
        await self.log(f"start_key_press_list")
        key_press_controller = KeyPressListController(task_list=self.task_list, ws_client=self.ws_client)
        await key_press_controller.start(extra_data=extra_data.get("extra_data", {}))
      
    await self.stop_all_task()  # 停止之前所有任务
    task = asyncio.create_task(run_schedule_task(schedule=schedule))
    self.add_task(task)  
    
  def parse_schedule_extra_data(self, schedule):
    extra_data = {}
    try:
      extra_data = json.loads(schedule.content)
    except Exception as e:
      pass
    return extra_data
    
  async def stop(self):
      """ 停止定时器 """
      await self.stop_all_task()  # 停止所有任务
